package com.zhl.study.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.time.LocalTime;

/**
 * @description Spring注解轻松搞定循环重试功能
 * @Author: z156940l@outlook.com
 * @className TestRetryService
 * @Date: 2023/4/26 16:44
 */
@Service
@Slf4j
public class TestRetryService {

    /**
     * Retryable注解说明
     *      value：根据命中的异常进行重试
     *      maxAttempts：最大重试次数
     *      backoff：
     *          delay：重试间隔的时间
     *          multiplier：倍数时间增长，这里配置1.5的意思是第一次间隔时间是两秒，第二次间隔是2*1.5三秒重试
     * @param code
     * @return
     * @throws Exception
     */
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public String test(int code) throws Exception {
        log.info("test被调用,时间：" + LocalTime.now());
        if (code == 0) {
            throw new Exception("调用失败啦！");
        }
        log.info("test被调用,真材实料！");

        return "200";
    }

    @Recover
    public String recover(Exception e, int code) {
        log.info("回调方法执行！！！！");
        log.info("{}", e.getMessage());
        return "400";
    }
}